//
//  AppDelegate.swift
//  weibo1
//
//  Created by changhongliang on 2017/7/20.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //打开数据库
        SQLiteManger.shareInstance.openDB(name: "status.sqlite")
       
        //初始化设置
        setupNavigationBar()
        //设置navigaitonbar
       UINavigationBar.appearance().tintColor = UIColor.orange
        //检查是否有新版本
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = defaultController()
        window?.backgroundColor = UIColor.white
        window?.makeKeyAndVisible()
        NotificationCenter.default.addObserver(self, selector:#selector(AppDelegate.switchRootViewController(n:)), name: NSNotification.Name(rawValue: HLSwitchMainInterfaceNotification), object: nil)
        return true
    }
    
    func setupNavigationBar()  {
        let navBar = UINavigationBar.appearance()
        var attr:Dictionary<String,AnyObject> = Dictionary<String,AnyObject>()
//        attr[NSForegroundColorAttributeName] = UIColor.orange
        attr[NSFontAttributeName] = UIFont.systemFont(ofSize: 17)
        navBar.titleTextAttributes = attr
    }
    
    ///判断是否有新版本
   private func isNewVersion() -> Bool {
    //1.从info.plist中获取当前版本的版本号 2.0
    let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
    
    //2.从沙盒中获取之前的版本号 1.0
    let userDefaults = UserDefaults.standard
    let sanboxVersion = userDefaults.object(forKey: "CFBundleShortVersionString") as? String ?? "0.0.0"
    
    //3.利用"当前的"和"沙盒"的进行比较
    if currentVersion.compare(sanboxVersion) == ComparisonResult.orderedDescending{
        // 有新版本
        //如果当前的大于沙盒的,则有新版本
        //如果有新版本,存储新版本
        userDefaults.set(currentVersion, forKey: "CFBundleShortVersionString")
        userDefaults.synchronize()
        return true
    }
        return false
    }
    
    //要显示的默认控制器
    private func defaultController()->UIViewController{
        if UserAccount.loadUserAccount() != nil {
            return isNewVersion() ? NewfeatureViewController():WelcomeViewController()
        }
        return MainViewController()
    
    }
    
    func switchRootViewController(n:Notification){
        let isMain = n.object as! Bool
        UIApplication.shared.keyWindow?.rootViewController = isMain ? MainViewController() :WelcomeViewController()
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
//        HLLog("程序进入后台")
//      HomeViewController.clearCacheStatus()
    }


   
}

